import 'package:flutter/material.dart';
import 'package:pull_to_refresh/pull_to_refresh.dart';
import 'package:tender_flutter/constant/app_config.dart';
import 'package:tender_flutter/constant/theme_colors.dart';
import 'package:tender_flutter/http/api_response.dart';
import 'package:tender_flutter/page/common/helper/data_manager.dart';
import 'package:tender_flutter/page/supplier/api/api_supplier.dart';
import 'package:tender_flutter/page/supplier/item/supplier_list_cell.dart';
import 'package:tender_flutter/page/supplier/model/supplier_entity.dart';
import 'package:tender_flutter/router/router.dart';
import 'package:tender_flutter/router/router_map.gr.dart';
import 'package:tender_flutter/utils/screen_adaper.dart';
import 'package:tender_flutter/widgets/load_state_layout.dart';

class SupplierListHomePage extends StatefulWidget {
  /// 供应商类型 参见：AppConstant
  final int supplietType;

  const SupplierListHomePage({Key key, this.supplietType}) : super(key: key);

  @override
  SupplierListHomePageState createState() => SupplierListHomePageState();
}

class SupplierListHomePageState extends State<SupplierListHomePage>
    with AutomaticKeepAliveClientMixin {
  RefreshController _refreshController =
      RefreshController(initialRefresh: false);

  /// 列表数据
  List<SupplierList> _listDatas = [];

  LoadState _loadState = LoadState.State_Loading;

  Future _listFuture;

  int page = AppConfig.page;

  int pageCount = AppConfig.pageCount;

  ///  是否需要刷新数据
  bool isNeedRefreshData = false;

  bool isInit = false;

  /// 刷新数据
  /// synchronous 是否立即刷新
  void updateData(bool synchronous) {
    if (synchronous) {
      if (_loadState == LoadState.State_Success) {
        if (_refreshController != null && isInit) {
          _refreshController.requestRefresh();
        } else {
          _onRefresh();
        }
      } else {
        _onRefresh();
      }
      isNeedRefreshData = false;
    } else {
      /// 定义需要刷新
      isNeedRefreshData = true;
    }
  }

  ///下拉刷新
  void _onRefresh() {
    isNeedRefreshData = false;
    page = 1;
    setState(() {
      _listFuture = _getData();
    });
  }

  /// 加载更多
  void _onLoading() {
    page += 1;
    setState(() {
      _listFuture = _getData();
    });
  }

  /// 获取数据
  Future<ApiResponse<SupplierEntity>> _getData() async {
    var response = await ApiSupplier.getSupplierList<SupplierEntity>(
      areaCode: DataManager.instance.cityEntity == null
          ? null
          : DataManager.instance.cityEntity.id,
      type: widget.supplietType,
      page: page,
      pageCount: pageCount,
    );
    return response;
  }

  FutureBuilder<ApiResponse<SupplierEntity>> _buildFutureBuilder() {
    return FutureBuilder(
        future: _listFuture,
        builder: (BuildContext context,
            AsyncSnapshot<ApiResponse<SupplierEntity>> snapshot) {
          if (snapshot.connectionState == ConnectionState.done) {
            if (snapshot.hasData) {
              SupplierEntity entity = snapshot.data.result;
              if (snapshot.data.status == Status.SUCCESS) {
                List temps = entity.xList == null ? [] : entity.xList;
                page == AppConfig.page
                    ? _listDatas = temps
                    : _listDatas += temps;
                if (_listDatas.isEmpty) {
                  _loadState = LoadState.State_Empty;
                } else {
                  _loadState = LoadState.State_Success;
                }
              } else {
                _loadState = LoadState.State_Error;
              }
            } else if (snapshot.hasError) {
              _loadState = LoadState.State_Error;
            }

            /// 结束刷新，处理分页
            if (_listDatas.length % AppConfig.pageCount != 0) {
              _refreshController.loadNoData();
            } else {
              if (_refreshController.isLoading) {
                _refreshController.loadComplete();
              }
            }
            if (_refreshController.isRefresh) {
              _refreshController.refreshCompleted();
            }
          }

          return LoadStateLayout(
            state: _loadState,
            successWidget: _initListView(),
          );
        });
  }

  @override
  bool get wantKeepAlive => true;

  @override
  void initState() {
    super.initState();
    _listFuture = _getData();
    WidgetsBinding.instance.addPostFrameCallback((mag) {
      isInit = true;
    });
  }

  @override
  Widget build(BuildContext context) {
    super.build(context);
    return _buildFutureBuilder();
  }

  /// 主体内容列表
  Widget _initListView() {
    return Container(
        margin: EdgeInsets.only(top: ScreenAdapter.height(15)),
        child: SmartRefresher(
            controller: _refreshController,
            enablePullUp: true,
            enablePullDown: true,
            onRefresh: _onRefresh,
            onLoading: _onLoading,
            child: ListView.separated(
              // physics: const ClampingScrollPhysics(),
              // controller: _controller,
              itemCount: _listDatas.length,
              itemBuilder: (BuildContext context, int index) {
                SupplierList model = _listDatas[index];
                return SupplierListCell(
                    data: model,
                    onTap: () {
                      LRouter.navigatorCtx(context).push(
                          Routes.supplierDetailPage,
                          arguments: SupplierDetailPageArguments(
                              supplierId: model.id));
                    });
              },
              separatorBuilder: (BuildContext context, int index) {
                return Divider(
                  height: ScreenAdapter.height(15),
                  color: ThemeColors.colorType11,
                );
              },
            )));
  }
}
